{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3.3 CartPoleの状態を離散化してみる"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 使用するパッケージの宣言\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline\n",
    "import gym\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定数の設定\n",
    "ENV = 'CartPole-v0'  # 使用する課題名\n",
    "NUM_DIZITIZED = 6  # 各状態の離散値への分割数\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "observation: (array([ 0.01384499, -0.01266305,  0.01563206, -0.0282749 ], dtype=float32), {})\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/bowen/soft/anaconda3/lib/python3.7/site-packages/gym/envs/registration.py:556: UserWarning: \u001b[33mWARN: The environment CartPole-v0 is out of date. You should consider upgrading to version `v1`.\u001b[0m\n",
      "  f\"The environment {id} is out of date. You should consider \"\n"
     ]
    }
   ],
   "source": [
    "# CartPoleを実行してみる\n",
    "env = gym.make(ENV)  # 実行する課題を設定\n",
    "observation = env.reset()  # 環境の初期化\n",
    "print(\"observation:\", observation)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 離散化の閾値を求める\n",
    "\n",
    "\n",
    "def bins(clip_min, clip_max, num):\n",
    "    '''観測した状態（連続値）を離散値にデジタル変換する閾値を求める'''\n",
    "    return np.linspace(clip_min, clip_max, num + 1)[1:-1]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([-2.4, -1.6, -0.8,  0. ,  0.8,  1.6,  2.4])"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.linspace(-2.4, 2.4, 6 + 1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([-1.6, -0.8,  0. ,  0.8,  1.6])"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.linspace(-2.4, 2.4, 6 + 1)[1:-1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "def digitize_state(observation):\n",
    "    '''観測したobservation状態を、離散値に変換する'''\n",
    "    print(\"observation:\", observation)\n",
    "    cart_pos, cart_v, pole_angle, pole_v = observation\n",
    "    digitized = [\n",
    "        np.digitize(cart_pos, bins=bins(-2.4, 2.4, NUM_DIZITIZED)),\n",
    "        np.digitize(cart_v, bins=bins(-3.0, 3.0, NUM_DIZITIZED)),\n",
    "        np.digitize(pole_angle, bins=bins(-0.5, 0.5, NUM_DIZITIZED)),\n",
    "        np.digitize(pole_v, bins=bins(-2.0, 2.0, NUM_DIZITIZED))]\n",
    "    return sum([x * (NUM_DIZITIZED**i) for i, x in enumerate(digitized)])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "ename": "ValueError",
     "evalue": "not enough values to unpack (expected 4, got 2)",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-17-4a14d9b3f711>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mdigitize_state\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mobservation\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;32m<ipython-input-16-5eb0eded0817>\u001b[0m in \u001b[0;36mdigitize_state\u001b[0;34m(observation)\u001b[0m\n\u001b[1;32m      1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mdigitize_state\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mobservation\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      2\u001b[0m     \u001b[0;34m'''観測したobservation状態を、離散値に変換する'''\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m     \u001b[0mcart_pos\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mcart_v\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mpole_angle\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mpole_v\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mobservation\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m      4\u001b[0m     digitized = [\n\u001b[1;32m      5\u001b[0m         \u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mdigitize\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcart_pos\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mbins\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mbins\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m2.4\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m2.4\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mNUM_DIZITIZED\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mValueError\u001b[0m: not enough values to unpack (expected 4, got 2)"
     ]
    }
   ],
   "source": [
    "digitize_state(observation)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
